/**
 * Copyright (c) 2011 Alexander De Leon Battista
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package es.upm.oeg.presto.resolver;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Status;
import org.restlet.representation.OutputRepresentation;

import es.upm.oeg.presto.api.RepresentationAPI;
import es.upm.oeg.presto.rewrite.URISpaceMapping;

/**
 * @author Alexander De Leon
 */
public class URISpaceHandler extends Restlet {

	private final ContentNegociator contentNegociator;
	private final RepresentationRegistry mediaTypeRegistry;
	private final URISpaceMapping mapping;

	private final Pattern documentUriPattern = Pattern.compile("^(.*)\\.(\\w+)$");
	private final ThreadLocal<Matcher> matcher = new ThreadLocal<Matcher>();

	public URISpaceHandler(ContentNegociator contentNegociator, RepresentationRegistry mediaTypeRegistry,
			URISpaceMapping mapping) {
		super();
		this.contentNegociator = contentNegociator;
		this.mediaTypeRegistry = mediaTypeRegistry;
		this.mapping = mapping;
	}

	@Override
	public void handle(Request request, Response response) {
		String uri = getRequestedUri(request);
		if (isResourceUri(uri)) {
			sendRedirectToDocument(uri, request, response);
		} else {
			provideResourceRepresentation(uri, request, response);
		}
		matcher.set(null);
	}

	protected void provideResourceRepresentation(String requestedUri, Request request, Response response) {
		String extension = getDocumentExtension(requestedUri);
		if (extension == null) {
			// TODO: exception
		}
		final String resourceUri = mapping.rewrite(getResourceUri(requestedUri));
		if (resourceUri == null) {
			// TODO: exception
		}
		Collection<RepresentationAPI> representations = mediaTypeRegistry.getRepresentations(extension);
		final RepresentationAPI representation = contentNegociator.getPrerredMediatype(request, representations);
		if (!representation.hasData(resourceUri)) {
			response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
		} else {

			response.setEntity(new OutputRepresentation(representation.getMediaType()) {
				@Override
				public void write(final OutputStream outputStream) throws IOException {
					representation.writeRepresentation(resourceUri, outputStream);
				}
			});
		}
	}

	protected void sendRedirectToDocument(String uri, Request request, Response response) {
		RepresentationAPI preferredMediaType = contentNegociator.getPrerredMediatype(request);
		if (preferredMediaType != null) {
			response.redirectSeeOther(uri + "." + preferredMediaType.getShortName());
		} else {
			// TODO: is this the best way to handle this?
			response.setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
		}
	}

	protected String getRequestedUri(Request request) {
		return request.getOriginalRef().toString(false, true);
	}

	protected boolean isResourceUri(String uri) {
		return !getMather(uri).matches();
	}

	private String getResourceUri(String requestedUri) {
		return getMather(requestedUri).group(1);
	}

	private String getDocumentExtension(String requestedUri) {
		return getMather(requestedUri).group(2);
	}

	private Matcher getMather(String requestUri) {
		if (matcher.get() == null) {
			matcher.set(documentUriPattern.matcher(requestUri));
		}
		return matcher.get();
	}
}
